angular.module('BaseServer')
    .factory('ImageCompress', ['$q', function($q) {
        var o = {};
        o._createImage = function(uri, options) {
            this.options = angular.extend(options, {
                type: 'image/jpeg',
                maxWidth: 250,
                maxHeight: 250
            });

            var defer = $q.defer();
            var img = new Image();
            var _this = this;

            function tmpLoad() {
                var dt = defer.resolve(o._drawImage(this));
                return dt;
            }

            img.onload = tmpLoad;
            img.src = uri;
            return defer.promise;
        };

        o._drawImage = function(img, callback) {
            this.sw = img.width;
            this.sh = img.height;
            this.tw = img.width;
            this.th = img.height;

            this.scale = (this.tw / this.th).toFixed(2);

            if (this.sw > this.options.maxWidth) {
                this.sw = this.options.maxWidth;
                this.sh = Math.round(this.sw / this.scale);
            }

            if (this.sh > this.options.maxHeight) {
                this.sh = this.options.maxHeight;
                this.sw = Math.round(this.sh * this.scale);
            }

            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');

            canvas.width = this.sw;
            canvas.height = this.sh;

            ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, this.sw, this.sh);

            var uri = canvas.toDataURL(this.options.type);
            ctx.clearRect(0, 0, this.tw, this.th);
            canvas.width = 0;
            canvas.height = 0;
            canvas = null;

            return uri;
        };
        return o;
    }]);